package com.open.rbac.config.security.handler;

import java.io.IOException;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.open.center.common.model.CommonResult;
import com.open.center.common.util.JSON;

/**
 * 认证失败处理
 *
 * @author Riche's
 * @since 2022/8/15
 */
@Service
public class MeAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().write(JSON.toJson(CommonResult
                .fail(StringUtils.hasText(authException.getMessage())
                        ? authException.getMessage() : "Token认证失败")));
        response.getWriter().flush();
        response.getWriter().close();
    }

}
